//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.farm.lucene.server;

import com.farm.lucene.common.IRResult;
import com.farm.lucene.common.IqlAnalyse;
import com.farm.lucene.common.IqlAnalyseInter;
import com.farm.lucene.common.ScoreDocFilterInter;
import com.farm.lucene.constant.IndexConf;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.IndexNotFoundException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class DocQueryImpl implements DocQueryInter {
	static boolean IsQueryAble = true;
	private static Logger log = Logger.getLogger(DocQueryImpl.class);
	private File indexFile = null;
	private List<File> indexFiles = null;

	private DocQueryImpl() {
	}

	public static DocQueryInter getInstance(File indexFile) {
		DocQueryImpl docQuery = new DocQueryImpl();
		docQuery.indexFile = indexFile;
		docQuery.indexFiles = new ArrayList();
		docQuery.indexFiles.add(indexFile);
		return docQuery;
	}

	public static DocQueryInter getInstance(List<File> indexFiles) {
		DocQueryImpl docQuery = new DocQueryImpl();
		docQuery.indexFiles = indexFiles;
		return docQuery;
	}

	public IRResult query(String Iql, int currentPage, int pagesize) throws Exception {
		if (!IsQueryAble) {
			return IRResult.getInstance(1);
		} else {
			IndexSearcher searcher = null;
			Directory directory = null;
			IRResult Result = null;
			IndexReader reade = null;
			long startTime = (new Date()).getTime();

			try {
				log.debug("EXCUTE-IQL:" + Iql + " at " + this.indexFile.getPath());
				IqlAnalyseInter iqlAnalyse = new IqlAnalyse(Iql, currentPage, pagesize);
				directory = FSDirectory.open(this.indexFile);
				reade = IndexReader.open(directory);
				searcher = new IndexSearcher(reade);
				QueryParser mqp = new MultiFieldQueryParser(Version.LUCENE_35, iqlAnalyse.getLimitTitle(),
						new IKAnalyzer());
				Query qp = mqp.parse(iqlAnalyse.getLimitValue());
				Sort sort = iqlAnalyse.getSortTitle();
				TopFieldDocs search = searcher.search(qp, iqlAnalyse.getMaxTopNum(), sort);
				ScoreDoc[] sco = search.scoreDocs;
				int totleSize = sco.length;
				sco = iqlAnalyse.subDoc(sco);
				List<Map<String, Object>> list = new ArrayList();
				int i = 0;

				while (true) {
					if (i >= sco.length) {
						Result = IRResult.getInstance(currentPage);
						Result.setPageSize(pagesize);
						Result.setTotleSize(totleSize);
						Result.setResultList(list);
						break;
					}

					Document targetDoc = searcher.doc(sco[i].doc);
					list.add(this.splitDoc(targetDoc, qp, iqlAnalyse.getLimitTitle()));
					++i;
				}
			} catch (IOException var33) {
				log.error("商品索引检索：" + var33.getMessage());
				throw new RuntimeException(var33.getMessage());
			} finally {
				if (searcher != null) {
					try {
						searcher.close();
					} catch (IOException var32) {
						log.error(var32.getMessage());
					}
				}

				if (directory != null) {
					try {
						directory.close();
					} catch (IOException var31) {
						log.error(var31.getMessage());
					}
				}

				if (reade != null) {
					try {
						reade.close();
					} catch (IOException var30) {
						log.error(var30.getMessage());
					}
				}

			}

			long endTime = (new Date()).getTime();
			log.debug("共检索到记录" + Result.getTotleSize() + "条，用时" + (endTime - startTime) + "毫秒");
			Result.setRuntime(endTime - startTime);
			Result.setTotalPage((Result.getTotleSize() - 1) / Result.getPageSize() + 1);
			return Result;
		}
	}

	protected Map<String, Object> splitDoc(Document node, Query query, String[] fields) throws Exception {
		Map<String, Object> map = new HashMap();
		SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
				IndexConf.getString("config.file.lucene_highLight_simple_s"),
				IndexConf.getString("config.file.lucene_highLight_simple_e"));
		Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
		Iterator var8 = node.getFields().iterator();

		while (var8.hasNext()) {
			Fieldable feild = (Fieldable) var8.next();
			String title = feild.name().toUpperCase();
			String value = node.get(feild.name());
			if (title.equals("ID")) {
				map.put(title, value);
			} else {
				if (ArrayUtils.contains(fields, title)) {
					String highLight = null;
					int textLength = Integer.valueOf(IndexConf.getString("config.file.lucene_highLight_maxnum"))
							.intValue();
					if (value.length() > textLength) {
						value = value.substring(0, textLength);
					}

					highlighter.setTextFragmenter(new SimpleFragmenter(
							Integer.valueOf(IndexConf.getString("config.file.lucene_highLight_maxnum")).intValue()));
					String text = node.get(title).replace("\n", "").replace("\t", "").replace(" ", "");
					IKAnalyzer analyzer = new IKAnalyzer();

					try {
						TokenStream tokenStream = analyzer.tokenStream(title.toUpperCase(), new StringReader(text));

						try {
							highLight = highlighter.getBestFragment(tokenStream, text);
						} catch (IOException var25) {
							log.error(var25.getMessage());
						} finally {
							tokenStream.close();
						}
					} finally {
						analyzer.close();
					}

					if (highLight != null) {
						value = highLight;
					}
				}

				map.put(title, value);
			}
		}

		return map;
	}

	public IRResult queryByMultiIndex(String Iql, int currentPage, int pagesize, ScoreDocFilterInter filter)
			throws Exception {
		if (!IsQueryAble) {
			return IRResult.getInstance(1);
		} else {
			IndexSearcher searcher = null;
			Directory directory = null;
			IRResult Result = null;
			IndexReader[] readers = null;
			long startTime = (new Date()).getTime();

			try {
				log.debug("EXCUTE-IQL:" + Iql + " at " + this.indexFiles);
				IqlAnalyseInter iqlAnalyse = new IqlAnalyse(Iql, currentPage, pagesize);
				QueryParser mqp = new MultiFieldQueryParser(Version.LUCENE_35, iqlAnalyse.getLimitTitle(),
						new IKAnalyzer());
				Query qp = mqp.parse(iqlAnalyse.getLimitValue());
				Sort sort = iqlAnalyse.getSortTitle();
				readers = new IndexReader[this.indexFiles.size()];

				for (int i = 0; i < this.indexFiles.size(); ++i) {
					if (!((File) this.indexFiles.get(i)).isDirectory()) {
						DocIndexImpl.getInstance((File) this.indexFiles.get(i)).close();
					}

					directory = FSDirectory.open((File) this.indexFiles.get(i));

					try {
						IndexReader reade = IndexReader.open(directory);
						readers[i] = reade;
					} catch (IndexNotFoundException var41) {
						throw new RuntimeException("没有找到索引文件，请先创建索引文件!");
					}
				}

				MultiReader mr = new MultiReader(readers);
				searcher = new IndexSearcher(mr);
				TopFieldDocs search = searcher.search(qp, iqlAnalyse.getMaxTopNum(), sort);
				ScoreDoc[] sco = search.scoreDocs;
				List<ScoreDoc> scolist1 = new ArrayList();
				ScoreDoc[] var22 = sco;
				int i = sco.length;

				for (int var20 = 0; var20 < i; ++var20) {
					ScoreDoc node = var22[var20];
					if (filter.doScan(searcher.doc(node.doc))) {
						scolist1.add(node);
					}
				}

				int totleSize = scolist1.size();
				List<ScoreDoc> scolist = iqlAnalyse.subDoc(scolist1);
				List<Map<String, Object>> list = new ArrayList();
				i = 0;

				while (true) {
					if (i >= scolist.size()) {
						Result = IRResult.getInstance(currentPage);
						Result.setPageSize(pagesize);
						Result.setTotleSize(totleSize);
						Result.setResultList(list);
						break;
					}

					Document targetDoc = searcher.doc(((ScoreDoc) scolist.get(i)).doc);
					list.add(this.splitDoc(targetDoc, qp, iqlAnalyse.getLimitTitle()));
					++i;
				}
			} catch (IOException var42) {
				log.error("商品索引检索：" + var42.getMessage());
				throw new RuntimeException(var42.getMessage());
			} finally {
				if (searcher != null) {
					try {
						searcher.close();
					} catch (IOException var40) {
						log.error(var40.getMessage());
					}
				}

				if (directory != null) {
					try {
						directory.close();
					} catch (IOException var39) {
						log.error(var39.getMessage());
					}
				}

				IndexReader[] var27 = readers;
				int var26 = readers.length;

				for (int var25 = 0; var25 < var26; ++var25) {
					IndexReader reader = var27[var25];

					try {
						if (reader != null) {
							reader.close();
						}
					} catch (IOException var38) {
						log.error(var38.getMessage());
					}
				}

			}

			long endTime = (new Date()).getTime();
			log.debug("共检索到记录" + Result.getTotleSize() + "条，用时" + (endTime - startTime) + "毫秒");
			Result.setRuntime(endTime - startTime);
			Result.setTotalPage((Result.getTotleSize() - 1) / Result.getPageSize() + 1);
			return Result;
		}
	}

	public IRResult queryByMultiIndex(String Iql, int currentPage, int pagesize) throws Exception {
		return this.queryByMultiIndex(Iql, currentPage, pagesize, new ScoreDocFilterInter() {
			public boolean doScan(Document document) {
				return true;
			}
		});
	}
}
